package com.logicbus.backend.websocket;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 演示代码
 *
 * @since 1.6.14.1 [20210310 duanyy] <br>
 */
@ServerEndpoint(value="/ws")
public class WSEndpointDemo extends WSEndpointBase2 {

    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        if (!doOpen(session,config)){
            LOG.info("WebSocket connect:{}",session.getRequestURI());
            RemoteEndpoint.Basic basic = session.getBasicRemote();
            try {
                basic.sendText("hello,this is a demo websocket service.");
                basic.sendText("This connection will be closed.88");
                session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT,"It is just a demo."));
            }catch (Exception ex){
                LOG.error("Failed to send message:" + ex.getMessage());
            }
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason reason){
        if (!doClose(session,reason)){
            LOG.info("WebSocket closed:{}-{}",reason.getCloseCode().getCode(),reason.getReasonPhrase());
        }
    }

    @OnError
    public void onError(Session session,Throwable t){
        if (!doError(session,t)){
            LOG.info("WebSocket error:{}",t.getMessage());
        }
    }

    @OnMessage
    public void onText(Session session,String msg)throws IOException {
        if (!doText(session,msg)){
            LOG.info("Text = {}",msg);
            RemoteEndpoint.Basic basic = session.getBasicRemote();
            basic.sendText(msg);
        }
    }

    @OnMessage
    public void onData(Session session,byte[]data) throws IOException{
        if (!doData(session,data)){
            LOG.info("Data = {}",new String(data));
            RemoteEndpoint.Basic basic = session.getBasicRemote();
            basic.sendBinary(ByteBuffer.wrap(data));
        }
    }
}
